<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="用户名" prop="username">
                      <el-input
                          v-model="queryParams.username"
                          placeholder="用户名"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                      <el-input
                          v-model="queryParams.password"
                          placeholder="密码"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="姓名" prop="fullname">
                      <el-input
                          v-model="queryParams.fullname"
                          placeholder="姓名"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="性别,0-未知,1-男,2-女" prop="gender">
                          <dict v-model="queryParams.gender" code="gender" />
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                      <el-input
                          v-model="queryParams.mobile"
                          placeholder="手机号"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="年级" prop="grade">
                      <el-input
                          v-model="queryParams.grade"
                          placeholder="年级"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="微信ID" prop="wechatId">
                      <el-input
                          v-model="queryParams.wechatId"
                          placeholder="微信ID"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="QQ号" prop="qq">
                      <el-input
                          v-model="queryParams.qq"
                          placeholder="QQ号"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="最后成绩" prop="lastScore">
                      <el-input
                          v-model="queryParams.lastScore"
                          placeholder="最后成绩"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="有效时长" prop="effectiveDuration">
                      <el-select
                          v-model="queryParams.effectiveDuration"
                          placeholder="请选择有效时长（月）"
                          clearable
                      >
                        <el-option :label="'3个月'" :value="3" />
                        <el-option :label="'6个月'" :value="6" />
                        <el-option :label="'9个月'" :value="9" />
                        <el-option :label="'12个月'" :value="12" />
                      </el-select>
                </el-form-item>
                <el-form-item label="账号过期时间" prop="expireTime">
                      <el-date-picker
                          v-model="queryParams.expireTime"
                          type="daterange"
                          range-separator="~"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                </el-form-item>
                <el-form-item label="最近登录时间" prop="loginTime">
                      <el-date-picker
                          v-model="queryParams.loginTime"
                          type="daterange"
                          range-separator="~"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                </el-form-item>
                <el-form-item label="电子邮箱" prop="email">
                      <el-input
                          v-model="queryParams.email"
                          placeholder="电子邮箱"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="关联年级列表" prop="grades">
                      <el-input
                          v-model="queryParams.grades"
                          placeholder="关联年级列表"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="学生类型,1=学生,2=其他" prop="studentType">
                      <el-input
                          v-model="queryParams.studentType"
                          placeholder="学生类型,1=学生,2=其他"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="首次登录时间" prop="firstLoginTime">
                      <el-date-picker
                          v-model="queryParams.firstLoginTime"
                          type="daterange"
                          range-separator="~"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                </el-form-item>
                <el-form-item label="教师姓名" prop="teacherName">
                      <el-input
                          v-model="queryParams.teacherName"
                          placeholder="教师姓名"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item v-if="canManageTeacher" label="归属老师" prop="teacherId">
                      <el-select
                          v-model="queryParams.teacherId"
                          placeholder="归属老师"
                          clearable
                          filterable
                          :loading="teacherOptionsLoading"
                          @visible-change="handleTeacherSelectVisibleChange"
                      >
                        <el-option
                            v-for="item in teacherOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                      </el-select>
                </el-form-item>
                <el-form-item label="教师手机号" prop="teacherMobile">
                      <el-input
                          v-model="queryParams.teacherMobile"
                          placeholder="教师手机号"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="班级名称" prop="className">
                      <el-input
                          v-model="queryParams.className"
                          placeholder="班级名称"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="状态,1=正常,0=禁用" prop="status">
                      <el-input
                          v-model="queryParams.status"
                          placeholder="状态,1=正常,0=禁用"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            v-hasPerm="['dcyx:dcyx-users:add']"
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
            v-hasPerm="['dcyx:dcyx-users:batch-add-accounts']"
            type="warning"
            @click="handleOpenBatchDialog()"
        >
          <template #icon><DocumentAdd /></template>
          批量创建账号
        </el-button>
        <el-button
            v-hasPerm="['dcyx:dcyx-users:assign-teacher-batch']"
            v-if="canAssignTeacherBatch"
            type="primary"
            :disabled="selectedUserIds.length === 0"
            @click="handleBatchAssign()"
        >
          <template #icon><User /></template>
          批量分配
        </el-button>
        <el-button
            v-hasPerm="['dcyx:dcyx-users:delete']"
            type="danger"
            :disabled="selectedUserIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
                    <el-table-column
                        key="id"
                        label="用户ID"
                        prop="id"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="organizationId"
                        label="所属组织ID"
                        prop="organizationId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="username"
                        label="用户名"
                        prop="username"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="password"
                        label="密码"
                        prop="password"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="fullname"
                        label="姓名"
                        prop="fullname"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column label="性别,0-未知,1-男,2-女" width="150" align="center">
                      <template #default="scope">
                        <DictLabel v-model="scope.row.gender" code="gender" />
                      </template>
                    </el-table-column>
                    <el-table-column
                        key="mobile"
                        label="手机号"
                        prop="mobile"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="schoolName"
                        label="学校名称"
                        prop="schoolName"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="grade"
                        label="年级"
                        prop="grade"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="wechatId"
                        label="微信ID"
                        prop="wechatId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="qq"
                        label="QQ号"
                        prop="qq"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="lastScore"
                        label="最后成绩"
                        prop="lastScore"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="expireTime"
                        label="账号过期时间"
                        prop="expireTime"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="loginTime"
                        label="最近登录时间"
                        prop="loginTime"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="email"
                        label="电子邮箱"
                        prop="email"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="effectiveDuration"
                        label="有效时长"
                        prop="effectiveDuration"
                        min-width="120"
                        align="center"
                    >
                      <template #default="scope">
                        <span v-if="scope.row.effectiveDuration">{{ scope.row.effectiveDuration }}个月</span>
                        <span v-else>-</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                        key="grades"
                        label="关联年级列表"
                        prop="grades"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="studentType"
                        label="学生类型,1=学生,2=其他"
                        prop="studentType"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="firstLoginTime"
                        label="首次登录时间"
                        prop="firstLoginTime"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="teacherName"
                        label="教师姓名"
                        prop="teacherName"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="assignedTeacherName"
                        label="归属老师"
                        min-width="150"
                        align="center"
                    >
                      <template #default="scope">
                        <span>{{ scope.row.assignedTeacherName || "-" }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                        key="teacherMobile"
                        label="教师手机号"
                        prop="teacherMobile"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="className"
                        label="班级名称"
                        prop="className"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="status"
                        label="状态,1=正常,0=禁用"
                        prop="status"
                        min-width="150"
                        align="center"
                    />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
                v-if="canAssignTeacher"
                v-hasPerm="'dcyx:dcyx-users:assign-teacher'"
                type="primary"
                size="small"
                link
                icon="User"
                @click="handleOpenAssignDialog([scope.row.id], scope.row.assignedTeacherId)"
            >
              分配老师
            </el-button>
            <el-button
                v-hasPerm="'dcyx:dcyx-users:reset-password'"
                type="primary"
                icon="RefreshLeft"
                size="small"
                link
                @click="hancleResetPassword(scope.row)"
              >
                重置密码
            </el-button>
            <el-button
                v-hasPerm="['dcyx:dcyx-users:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
                v-hasPerm="['dcyx:dcyx-users:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 批量创建账号 -->
    <el-dialog
        v-model="batchDialog.visible"
        title="批量创建账号"
        width="520px"
        @close="handleBatchDialogClose"
    >
      <el-form ref="batchFormRef" :model="batchForm" :rules="batchFormRules" label-width="110px">
        <el-form-item label="生成数量" prop="quantity">
          <el-input-number
              v-model="batchForm.quantity"
              :min="1"
              :max="200"
              :step="1"
              controls-position="right"
              placeholder="数量"
          />
        </el-form-item>
        <el-form-item label="有效时长" prop="effectiveDuration">
          <el-radio-group v-model="batchForm.effectiveDuration">
            <el-radio-button :label="3">3个月</el-radio-button>
            <el-radio-button :label="6">6个月</el-radio-button>
            <el-radio-button :label="9">9个月</el-radio-button>
            <el-radio-button :label="12">12个月</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div v-if="batchDialog.result.length" style="margin-top: 16px;">
        <el-alert
            :title="`已生成 ${batchDialog.result.length} 个账号`"
            type="success"
            show-icon
            style="margin-bottom: 12px;"
        />
        <el-table :data="batchDialog.result" size="small" border>
          <el-table-column prop="username" label="用户名" min-width="220" />
          <el-table-column prop="initialPassword" label="初始密码" min-width="120" />
          <el-table-column label="有效时长" min-width="120">
            <template #default="scope">
              {{ scope.row.effectiveDuration }}个月
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button :disabled="batchDialog.submitting" @click="handleBatchDialogClose()">取消</el-button>
        <el-button type="primary" :loading="batchDialog.submitting" @click="handleBatchCreateSubmit()">
          确认生成
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户信息表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
                <el-input type="hidden" v-model="formData.id" />
                <el-form-item label="所属组织ID" prop="organizationId">
                      <el-input
                          v-model="formData.organizationId"
                          placeholder="所属组织ID"
                      />
                </el-form-item>

                <el-form-item label="用户名" prop="username">
                      <el-input
                          v-model="formData.username"
                          placeholder="用户名"
                      />
                </el-form-item>

                <el-form-item label="密码" prop="password">
                      <el-input
                          v-model="formData.password"
                          placeholder="密码"
                      />
                </el-form-item>

                <el-form-item label="姓名" prop="fullname">
                      <el-input
                          v-model="formData.fullname"
                          placeholder="姓名"
                      />
                </el-form-item>

                <el-form-item label="性别,0-未知,1-男,2-女" prop="gender">
                          <dict v-model="formData.gender" code="gender" />
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                      <el-input
                          v-model="formData.mobile"
                          placeholder="手机号"
                      />
                </el-form-item>

                <el-form-item label="学校名称" prop="schoolName">
                      <el-input
                          v-model="formData.schoolName"
                          placeholder="学校名称"
                      />
                </el-form-item>

                <el-form-item label="年级" prop="grade">
                      <el-input
                          v-model="formData.grade"
                          placeholder="年级"
                      />
                </el-form-item>

                <el-form-item label="微信ID" prop="wechatId">
                      <el-input
                          v-model="formData.wechatId"
                          placeholder="微信ID"
                      />
                </el-form-item>

                <el-form-item label="QQ号" prop="qq">
                      <el-input
                          v-model="formData.qq"
                          placeholder="QQ号"
                      />
                </el-form-item>

                <el-form-item label="最后成绩" prop="lastScore">
                      <el-input
                          v-model="formData.lastScore"
                          placeholder="最后成绩"
                      />
                </el-form-item>

                <el-form-item label="账号过期时间" prop="expireTime">
                      <el-date-picker
                          v-model="formData.expireTime"
                          type="datetime"
                          placeholder="账号过期时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                </el-form-item>

                <el-form-item label="最近登录时间" prop="loginTime">
                      <el-date-picker
                          v-model="formData.loginTime"
                          type="datetime"
                          placeholder="最近登录时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                </el-form-item>

                <el-form-item label="电子邮箱" prop="email">
                      <el-input
                          v-model="formData.email"
                          placeholder="电子邮箱"
                      />
                </el-form-item>

                <el-form-item label="关联年级列表" prop="grades">
                      <el-input
                          v-model="formData.grades"
                          placeholder="关联年级列表"
                      />
                </el-form-item>

                <el-form-item label="学生类型,1=学生,2=其他" prop="studentType">
                      <el-input
                          v-model="formData.studentType"
                          placeholder="学生类型,1=学生,2=其他"
                      />
                </el-form-item>

                <el-form-item label="首次登录时间" prop="firstLoginTime">
                      <el-date-picker
                          v-model="formData.firstLoginTime"
                          type="datetime"
                          placeholder="首次登录时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                </el-form-item>

                <el-form-item label="教师姓名" prop="teacherName">
                      <el-input
                          v-model="formData.teacherName"
                          placeholder="教师姓名"
                      />
                </el-form-item>

                <el-form-item label="教师手机号" prop="teacherMobile">
                      <el-input
                          v-model="formData.teacherMobile"
                          placeholder="教师手机号"
                      />
                </el-form-item>

                <el-form-item label="班级名称" prop="className">
                      <el-input
                          v-model="formData.className"
                          placeholder="班级名称"
                      />
                </el-form-item>

                <el-form-item label="有效时长" prop="effectiveDuration">
                      <el-select
                          v-model="formData.effectiveDuration"
                          placeholder="请选择有效时长（月）"
                          clearable
                      >
                        <el-option :label="'3个月'" :value="3" />
                        <el-option :label="'6个月'" :value="6" />
                        <el-option :label="'9个月'" :value="9" />
                        <el-option :label="'12个月'" :value="12" />
                      </el-select>
                </el-form-item>

                <el-form-item label="状态,1=正常,0=禁用" prop="status">
                      <el-input
                          v-model="formData.status"
                          placeholder="状态,1=正常,0=禁用"
                      />
                </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="assignDialog.visible"
        :title="assignDialogTitle"
        width="400px"
        @close="handleAssignDialogClose"
    >
      <el-form label-width="100px">
        <el-form-item label="归属老师">
          <el-select
              v-model="assignForm.teacherId"
              placeholder="请选择归属老师"
              clearable
              filterable
              :loading="teacherOptionsLoading"
              @visible-change="handleTeacherSelectVisibleChange"
          >
            <el-option
                v-for="item in teacherOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="assignDialog.submitting" @click="handleAssignTeacherSubmit">
            确 定
          </el-button>
          <el-button :disabled="assignDialog.submitting" @click="handleAssignDialogClose">
            取 消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  defineOptions({
    name: "DcyxUsers",
    inheritAttrs: false,
  });

  import DcyxUsersAPI, {
    DcyxUsersPageVO,
    DcyxUsersForm,
    DcyxUsersPageQuery,
    AssignTeacherBatchResult,
    BatchCreateAccountsRequest,
    BatchCreatedAccount,
  } from "@/api/dcyx/dcyx-users";
  import type { FormInstance, FormRules } from "element-plus";
  import { useUserStoreHook } from "@/store/modules/user.store";

  const queryFormRef = ref();
  const dataFormRef = ref();
  const dataTableRef = ref();
  const batchFormRef = ref<FormInstance>();

  const loading = ref(false);
  const selectedUserIds = ref<number[]>([]);
  const total = ref(0);

  const userStore = useUserStoreHook();
  const userPerms = computed(() => userStore.userInfo.perms ?? []);
  const canAssignTeacher = computed(() => userPerms.value.includes("dcyx:dcyx-users:assign-teacher"));
  const canAssignTeacherBatch = computed(() => userPerms.value.includes("dcyx:dcyx-users:assign-teacher-batch"));
  const canManageTeacher = computed(() => canAssignTeacher.value || canAssignTeacherBatch.value);

  const teacherOptions = ref<OptionType[]>([]);
  const teacherOptionsLoading = ref(false);
  let teacherOptionsPromise: Promise<OptionType[]> | null = null;

  const assignDialog = reactive({
    visible: false,
    userIds: [] as number[],
    submitting: false,
  });

  const assignForm = reactive({
    teacherId: undefined as number | string | undefined,
  });

  const assignDialogTitle = computed(() =>
    assignDialog.userIds.length > 1 ? "批量分配归属老师" : "分配归属老师"
  );

  const queryParams = reactive<DcyxUsersPageQuery>({
    pageNum: 1,
    pageSize: 10,
  });

  // 用户信息表格数据
  const pageData = ref<DcyxUsersPageVO[]>([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });

  const batchDialog = reactive({
    visible: false,
    submitting: false,
    result: [] as BatchCreatedAccount[],
  });

  const batchForm = reactive<BatchCreateAccountsRequest>({
    quantity: 1,
    effectiveDuration: 3,
  });

  const batchFormRules = reactive<FormRules<BatchCreateAccountsRequest>>({
    quantity: [
      { required: true, message: "请输入生成数量", trigger: "blur" },
      {
        type: "number" as const,
        min: 1,
        max: 200,
        message: "数量需在1~200之间",
        trigger: "change",
      },
    ],
    effectiveDuration: [{ required: true, message: "请选择有效时长", trigger: "change" }],
  });

  // 用户信息表单数据
  const formData = reactive<DcyxUsersForm>({});

  // 用户信息表单校验规则
  const rules = reactive({
                      organizationId: [{ required: true, message: "请输入所属组织ID", trigger: "blur" }],
                      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
                      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
                      fullname: [{ required: true, message: "请输入姓名", trigger: "blur" }],
                      gender: [{ required: true, message: "请输入性别,0-未知,1-男,2-女", trigger: "blur" }],
                      mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
                      schoolName: [{ required: true, message: "请输入学校名称", trigger: "blur" }],
                      grade: [{ required: true, message: "请输入年级", trigger: "blur" }],
                      wechatId: [{ required: true, message: "请输入微信ID", trigger: "blur" }],
                      qq: [{ required: true, message: "请输入QQ号", trigger: "blur" }],
                      lastScore: [{ required: true, message: "请输入最后成绩", trigger: "blur" }],
                      expireTime: [{ required: true, message: "请输入账号过期时间", trigger: "blur" }],
                      loginTime: [{ required: true, message: "请输入最近登录时间", trigger: "blur" }],
                      email: [{ required: true, message: "请输入电子邮箱", trigger: "blur" }],
                      grades: [{ required: true, message: "请输入关联年级列表", trigger: "blur" }],
                      studentType: [{ required: true, message: "请输入学生类型,1=学生,2=其他", trigger: "blur" }],
                      firstLoginTime: [{ required: true, message: "请输入首次登录时间", trigger: "blur" }],
                      teacherName: [{ required: true, message: "请输入教师姓名", trigger: "blur" }],
                      teacherMobile: [{ required: true, message: "请输入教师手机号", trigger: "blur" }],
                      className: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
                      status: [{ required: true, message: "请输入状态,1=正常,0=禁用", trigger: "blur" }],
  });

  function resetBatchFormDefaults() {
    batchForm.quantity = 1;
    batchForm.effectiveDuration = 3;
  }

  function handleOpenBatchDialog() {
    resetBatchFormDefaults();
    batchDialog.visible = true;
    batchDialog.submitting = false;
    batchDialog.result = [];
    nextTick(() => {
      batchFormRef.value?.clearValidate?.();
    });
  }

  function handleBatchDialogClose() {
    batchDialog.visible = false;
    batchDialog.submitting = false;
    batchDialog.result = [];
    resetBatchFormDefaults();
    nextTick(() => {
      batchFormRef.value?.clearValidate?.();
    });
  }

  function handleBatchCreateSubmit() {
    if (!batchFormRef.value) {
      return;
    }
    batchFormRef.value.validate((valid: boolean) => {
      if (!valid) {
        return;
      }
      batchDialog.submitting = true;
      const payload: BatchCreateAccountsRequest = {
        quantity: batchForm.quantity,
        effectiveDuration: batchForm.effectiveDuration,
      };
      DcyxUsersAPI.batchCreateAccounts(payload)
        .then((data) => {
          const accounts = data ?? [];
          batchDialog.result = accounts;
          if (accounts.length > 0) {
            ElMessage.success(`成功创建 ${accounts.length} 个账号`);
          } else {
            ElMessage.success("创建成功");
          }
          handleQuery();
        })
        .finally(() => {
          batchDialog.submitting = false;
        });
    });
  }

  watch(
    canManageTeacher,
    (value) => {
      if (value) {
        getTeacherOptions();
      } else {
        teacherOptions.value = [];
      }
    },
    { immediate: true }
  );

  function getTeacherOptions(): Promise<OptionType[]> {
    if (teacherOptions.value.length > 0) {
      return Promise.resolve(teacherOptions.value);
    }
    if (teacherOptionsPromise) {
      return teacherOptionsPromise;
    }
    return fetchTeacherOptions();
  }

  function fetchTeacherOptions(): Promise<OptionType[]> {
    teacherOptionsLoading.value = true;
    teacherOptionsPromise = DcyxUsersAPI.listTeachers()
      .then((data) => {
        teacherOptions.value = data ?? [];
        return teacherOptions.value;
      })
      .finally(() => {
        teacherOptionsLoading.value = false;
        teacherOptionsPromise = null;
      });
    return teacherOptionsPromise;
  }

  function handleTeacherSelectVisibleChange(visible: boolean) {
    if (visible) {
      getTeacherOptions();
    }
  }

  /** 查询用户信息 */
  function handleQuery() {
    loading.value = true;
    DcyxUsersAPI.getPage(queryParams)
      .then(async (data) => {
        const list = data.list ?? [];
        const needTeacherInfo = list.some(
          (item) =>
            item &&
            item.assignedTeacherId !== undefined &&
            item.assignedTeacherId !== null &&
            !item.assignedTeacherName
        );

        if (needTeacherInfo) {
          try {
            await getTeacherOptions();
          } catch {
            // 忽略教师列表加载失败，保持已有数据
          }

          if (teacherOptions.value.length > 0) {
            const teacherMap = new Map<string, string>(
              teacherOptions.value.map((option) => [String(option.value), option.label])
            );
            list.forEach((item) => {
              if (item && item.assignedTeacherId !== undefined && item.assignedTeacherId !== null) {
                const label = teacherMap.get(String(item.assignedTeacherId));
                if (label) {
                  item.assignedTeacherName = label;
                }
              }
            });
          }
        }

        pageData.value = list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  /** 重置用户信息查询 */
  function handleResetQuery() {
    queryFormRef.value!.resetFields();
    queryParams.pageNum = 1;
    selectedUserIds.value = [];
    dataTableRef.value?.clearSelection?.();
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  function handleSelectionChange(selection: any) {
    selectedUserIds.value = selection.map((item: any) => item.id);
  }

  function handleOpenAssignDialog(
    userIds: Array<number | string | undefined | null>,
    teacherId?: number | string | null
  ) {
    const validIds = (userIds ?? [])
      .map((item) => {
        if (item === undefined || item === null || item === "") {
          return undefined;
        }
        const numericId = Number(item);
        return Number.isNaN(numericId) ? undefined : numericId;
      })
      .filter((item): item is number => item !== undefined);

    if (validIds.length === 0) {
      ElMessage.warning("请选择需要分配的学生");
      return;
    }

    getTeacherOptions();
    assignDialog.visible = true;
    assignDialog.userIds = validIds;
    assignForm.teacherId = teacherId ? String(teacherId) : undefined;
  }

  function handleBatchAssign() {
    handleOpenAssignDialog(selectedUserIds.value);
  }

  function handleAssignDialogClose() {
    assignDialog.visible = false;
    assignDialog.userIds = [];
    assignForm.teacherId = undefined;
    assignDialog.submitting = false;
  }

  function handleAssignTeacherSubmit() {
    if (!assignForm.teacherId) {
      ElMessage.warning("请选择归属老师");
      return;
    }

    assignDialog.submitting = true;
    const teacherId = assignForm.teacherId;
    const request =
      assignDialog.userIds.length === 1
        ? DcyxUsersAPI.assignTeacher(assignDialog.userIds[0], teacherId)
        : DcyxUsersAPI.assignTeacherBatch({
            teacherId,
            userIds: assignDialog.userIds,
          });

    request
      .then((result) => {
        if (assignDialog.userIds.length > 1) {
          const { updatedCount = 0, skippedCount = 0 } = result as AssignTeacherBatchResult;
          const message =
            skippedCount > 0
              ? `成功分配 ${updatedCount} 条，跳过 ${skippedCount} 条`
              : `成功分配 ${updatedCount} 条`;
          ElMessage.success(message);
        } else {
          ElMessage.success("分配成功");
        }
        handleAssignDialogClose();
        dataTableRef.value?.clearSelection?.();
        selectedUserIds.value = [];
        handleQuery();
      })
      .finally(() => {
        assignDialog.submitting = false;
      });
  }

  /** 打开用户信息弹窗 */
  function handleOpenDialog(id?: number) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改用户信息";
            DcyxUsersAPI.getFormData(id).then((data) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = "新增用户信息";
    }
  }

  /** 提交用户信息表单 */
  function handleSubmit() {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.id;
        if (id) {
                DcyxUsersAPI.update(id, formData)
              .then(() => {
                ElMessage.success("修改成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        } else {
                DcyxUsersAPI.add(formData)
              .then(() => {
                ElMessage.success("新增成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭用户信息弹窗 */
  function handleCloseDialog() {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.id = undefined;
  }

  /** 删除用户信息 */
  function handleDelete(id?: number) {
    const ids = id ? [id] : selectedUserIds.value;
    if (ids.length === 0) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
        () => {
          loading.value = true;
                DcyxUsersAPI.deleteByIds(ids.join(","))
              .then(() => {
                ElMessage.success("删除成功");
                selectedUserIds.value = [];
                dataTableRef.value?.clearSelection?.();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        },
        () => {
          ElMessage.info("已取消删除");
        }
    );
  }

    // 重置密码
  function hancleResetPassword(row: DcyxUsersPageVO) {
    ElMessageBox.prompt("请输入用户【" + row.username + "】的新密码", "重置密码", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }).then(
      ({ value }) => {
        if (!value || value.length < 6) {
          ElMessage.warning("密码至少需要6位字符，请重新输入");
          return false;
        }
        DcyxUsersAPI.resetPassword(String(row.id), value).then(() => {
          ElMessage.success("密码重置成功，新密码是：" + value);
        });
      },
      () => {
        ElMessage.info("已取消重置密码");
      }
    );
  }

  onMounted(() => {
    handleQuery();
  });
</script>
